#!/bin/bash
: <<COMMENT
  Copyright (C) 2012 Tri Le <trile7 at gmail dot com>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
COMMENT

log="logger -t tmpfs-sync -s"
ver="tmpfs v0.4.1"

function usage {
  echo -e "$ver\nUsage: $0 --config config_file readme|start|sync|stop"; exit 1
  }

function sync2disk() {
  [[ `readlink "$1"` = $tmp ]] || return 2
  [[ -d $tmp ]] && rsync -a --delete "$tmp/" "$backup/" ||  rsync "$tmp" "$backup"
  if [[ $? -eq 0 ]]; then
    $log "$1 synced"
  else
    $log "$1 fails to sync"; return 1
  fi
  }

function stopsync(){
  [[ -h $1 ]] && rm -f "$1"
  [[ -e $backup ]] && mv "$backup" "$1"
  [[ -e $tmp ]] && rm -rf "$tmp"
  }

function startsync(){
  [[ `readlink "$1"` = $tmp ]] && return 2
  if ! cp -a "$1" "$tmp"; then
    for j in {1..5}; do
      sleep 6
      cp -a "$1" "$tmp" && break
    done
    [[ $? -eq 0 ]] || return 1
  fi
  mv "$1" "$backup" || return 1
  ln -s "$tmp" "$1" || return 1
  }

if [[ $1 = --config ]]; then
  config=$2; shift 2
elif [[ $1 = readme ]]; then
  readme=`readlink -f "$0"`.readme
  cat "$readme"; exit 0
elif ! [[ $1 =~ start|stop|sync ]]; then
  usage
fi
if ! source "$config" &>/dev/null; then
  echo "Problem sourcing config file.  Please refer to readme to create config file or use sample config file at /usr/share/tmpfs-sync/tmpfs-sync.cfg"; exit 1
fi
if ! mount | grep -q "$tmpfs type tmpfs"; then
  echo "$tmpfs is not mounted as tmpfs"; exit 1
fi
action=$1
for i in "${sync_folders[@]}"; do
  backup=$i-backup
  tmp=$tmpfs/${i//\//_}
  case $action in
    start) if startsync "$i"; then $log "$i started"; else $log "$i fails to start"; stopsync "$i"; fi ;;
    stop) sync2disk "$i"; stopsync "$i"; $log "$i stopped" ;;
    sync) sync2disk "$i" ;;
  esac
done
